package com.yand.frame.common;



import com.yand.frame.entity.ActivityUser;
import com.yand.frame.service.LoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 *   shiro 的 Realm 类，用户对用户的校验
 */

public class MyShiroRealm extends AuthorizingRealm {


    @Autowired
    private LoginService loginService;
    /**
     * 认证权限
     *
     * 暂时不验证
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        return simpleAuthorizationInfo;
    }



    /**
     * 认证用户
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //获取用户的Token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //得到用户名
        String userName = token.getUsername();

        ActivityUser userInfo = loginService.getActivityUser(userName);

        //校验用户是否存在
        if(userInfo == null) {
            throw new IncorrectCredentialsException("用户名或密码不正确");
        }

        //这边校验用户名以及密码
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                userInfo, userInfo.getrPassword(), getName());
        return authenticationInfo;
    }
}
